package com.gitee.wsl.security.encrypt.sample

import com.gitee.wsl.ext.string.padding
import com.gitee.wsl.security.encrypt.Encrypt
import com.gitee.wsl.security.encrypt.StringToStringEncrypt
import kotlin.math.ceil

class CaesarBoxCipher(val height: Int): StringToStringEncrypt {

    override fun encrypt(src: String): String {
        return encrypt(src, height)
    }

    override fun decrypt(src: String): String {
        val height=ceil(src.length / height.toDouble()).toInt()
        return encrypt(src, height)
    }

    private fun encrypt(src: String,height: Int): String {
        val properData = src.replace(" ", "")
        val width = ceil(properData.length / height.toDouble()).toInt()
        val input = properData.padding(PADDING_CHAR.toString(), width)
        val sb = StringBuilder()
        for (i in 0 until height) {
            for (j in i until input.length step height) {
                if (input[j] != PADDING_CHAR) {
                    sb.append(input[j])
                }
            }
        }
        return sb.toString()
    }

    companion object{
        private const val PADDING_CHAR = 0.toChar()
    }
}

fun Encrypt.Companion.caesarBox(height: Int) = CaesarBoxCipher(height)



